﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
using Hrm.Services;
using Hrm.Core;
using Autofac;
using System.Security.Claims;
using Hrm.Web.Framework;

namespace Hrm.Web
{
    public class RoleAuthorizeAttribute:AuthorizeAttribute
    {

        public new List<string> Roles { get; set; }

        public RoleAuthorizeAttribute()
        {
        }

        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            if (httpContext == null)
            {
                throw new ArgumentNullException("HttpContext");
            }
            if (!httpContext.User.Identity.IsAuthenticated)
            {
                return false;
            }
            if (Roles == null)
            {
                return false;
            }
            if (Roles.Count == 0)
            {
                return true;
            }
            var data = httpContext.Request.GetOwinContext().Authentication.User.Claims;
            var entity = data.FirstOrDefault(a => a.Type == ClaimTypes.Role);
            if (entity != null)
            {
                string[] RoleCodes = entity.Value.Split(',');
                if (RoleCodes.Contains(Constant.AdministratorRoleCode) || Roles.Any(p => RoleCodes.Contains(p)))//当为超级管理员的时候 或者 有权限的时候
                {
                    return true;
                }
            }
            return false;
        }

        public override void OnAuthorization(System.Web.Mvc.AuthorizationContext filterContext)
        {
            var roleService = EngineContext.IocContext.Resolve<IRoleService>();
            object areaObject = filterContext.RouteData.DataTokens["area"];
            string areaName = areaObject == null ? string.Empty : areaObject.ToString();
            string controllerName = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName;
            string actionName = filterContext.ActionDescriptor.ActionName;
            
            var cacheManager = EngineContext.IocContext.Resolve<ICacheManager>();
            var cacheStr = string.Format(Constant.CacheAreaControlActionRoleCodes, areaName, controllerName, actionName);
            this.Roles = cacheManager.Get<List<string>>(cacheStr);
            if (Roles==null)
            {
                this.Roles = roleService.GetRoleCodesByResource(areaName, controllerName, actionName);
                cacheManager.Set(cacheStr, Roles, Constant.CacheTimeout);
            }
            base.OnAuthorization(filterContext);
        }

        protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
        {
            if(filterContext.HttpContext.User.Identity.IsAuthenticated)
            {
                //filterContext.HttpContext.Response.Redirect("/Home/Page403");
                filterContext.Result = new RedirectResult("/Home/Page403");
            }
            else
            {
                filterContext.Result = new RedirectResult("/Admin/Login");
            }
        }
    }
}
